package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * Title  : 450. Delete Node in a BST
 * Source : https://leetcode.cn/problems/delete-node-in-a-bst/description/
 * Author : XrazYang
 * Date   : 2024-04-22
 */

public class LeetCode_450 {

    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        } else {
            if (root.val < val) {
                root.right = insertIntoBST(root.right, val);
            }
            if (root.val > val) {
                root.left = insertIntoBST(root.left, val);
            }
        }
        return root;
    }

    /**
     * 朴素解法：
     * 遍历删除结点，再通过插入结点方法，重新构建二叉查找树(打败0.32%用户...)
     */
    public TreeNode deleteNode(TreeNode root, int key) {
        ArrayDeque<TreeNode> sta = new ArrayDeque<>();
        List<Integer> keys = new ArrayList<>();
        TreeNode current = root;
        while (current != null || !sta.isEmpty()) {
            if (current != null) {
                sta.push(current);
                current = current.left;
            } else {
                current = sta.pop();
                if (key != current.val) {
                    keys.add(current.val);
                }
                current = current.right;
            }
        }
        root = null;
        for (int i : keys) {
            root = insertIntoBST(root, i);
        }
        return root;
    }

    public TreeNode deleteNode2(TreeNode root, int key) {
        if (root == null) return null;
        if (root.val == key) {
            if (root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            } else {
                //该结点的直接后继：该结点右子树最左边结点
                TreeNode cur = root.right;
                while (cur.left != null) {
                    cur = cur.left;
                }
                cur.left = root.left;
                root = root.right;
                return root;
            }
        }
        if (root.val > key) root.left = deleteNode2(root.left, key);
        if (root.val < key) root.right = deleteNode2(root.right, key);
        return root;
    }
}
